import 'package:flutter/material.dart';

/// 购物车页面
/// 展示购物车商品列表，支持选择、修改数量、删除和结算
/// 学习StatefulWidget、ListView、Checkbox、AlertDialog等Widget的使用
class CartScreen extends StatefulWidget {
  const CartScreen({super.key});

  @override
  State<CartScreen> createState() => _CartScreenState();
}

/// 购物车页面的状态管理类
class _CartScreenState extends State<CartScreen> {
  /// 购物车商品列表
  /// 每个商品包含：id、名称、价格、图片、数量、是否选中
  final List<Map<String, dynamic>> _cartItems = [
    {
      'id': 1,
      'name': 'iPhone 15 Pro',
      'price': 7999.0,
      'image': '📱',
      'quantity': 1,
      'selected': true,
    },
    {
      'id': 2,
      'name': 'AirPods Pro',
      'price': 1999.0,
      'image': '🎧',
      'quantity': 2,
      'selected': true,
    },
    {
      'id': 3,
      'name': 'MacBook Air',
      'price': 8999.0,
      'image': '💻',
      'quantity': 1,
      'selected': false,
    },
  ];

  /// 是否全选
  bool _selectAll = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('购物车'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        elevation: 0,
        actions: [
          // 清空购物车按钮
          TextButton(
            onPressed: _cartItems.isNotEmpty ? _clearCart : null,
            child: const Text('清空'),
          ),
        ],
      ),
      body: _cartItems.isEmpty
          ? _buildEmptyCart() // 空购物车界面
          : Column(
              children: [
                // 购物车列表
                Expanded(child: _buildCartList()),
                // 底部结算栏
                _buildCheckoutBar(),
              ],
            ),
    );
  }

  /// 构建空购物车界面
  /// 当购物车为空时显示，引导用户去购物
  Widget _buildEmptyCart() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 空购物车图标
          Icon(Icons.shopping_cart_outlined, size: 80, color: Colors.grey[400]),
          const SizedBox(height: 16),
          // 提示文本
          Text(
            '购物车是空的',
            style: Theme.of(
              context,
            ).textTheme.headlineSmall?.copyWith(color: Colors.grey[600]),
          ),
          const SizedBox(height: 8),
          Text(
            '快去添加一些商品吧',
            style: Theme.of(
              context,
            ).textTheme.bodyMedium?.copyWith(color: Colors.grey[500]),
          ),
          const SizedBox(height: 24),
          // 去购物按钮
          ElevatedButton(
            onPressed: () {
              // 导航到商品页面
            },
            child: const Text('去购物'),
          ),
        ],
      ),
    );
  }

  /// 构建购物车列表
  /// 使用ListView.builder展示购物车商品
  Widget _buildCartList() {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _cartItems.length,
      itemBuilder: (context, index) {
        final item = _cartItems[index];
        return Card(
          margin: const EdgeInsets.only(bottom: 12),
          child: Padding(
            padding: const EdgeInsets.all(12),
            child: Row(
              children: [
                // 选择框 - 控制商品是否选中
                Checkbox(
                  value: item['selected'],
                  onChanged: (value) {
                    setState(() {
                      item['selected'] = value;
                      _updateSelectAll(); // 更新全选状态
                    });
                  },
                ),
                // 商品图片
                Container(
                  width: 60,
                  height: 60,
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.primaryContainer,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Center(
                    child: Text(
                      item['image'],
                      style: const TextStyle(fontSize: 24),
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                // 商品信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 商品名称
                      Text(
                        item['name'],
                        style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                          fontWeight: FontWeight.w600,
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 4),
                      // 商品价格
                      Text(
                        '¥${item['price']}',
                        style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                          color: Theme.of(context).colorScheme.primary,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
                // 数量控制
                Row(
                  children: [
                    // 减少数量按钮
                    IconButton(
                      icon: const Icon(Icons.remove_circle_outline),
                      onPressed: () {
                        setState(() {
                          if (item['quantity'] > 1) {
                            item['quantity']--;
                          }
                        });
                      },
                    ),
                    // 数量显示
                    Text(
                      '${item['quantity']}',
                      style: Theme.of(context).textTheme.bodyLarge,
                    ),
                    // 增加数量按钮
                    IconButton(
                      icon: const Icon(Icons.add_circle_outline),
                      onPressed: () {
                        setState(() {
                          item['quantity']++;
                        });
                      },
                    ),
                  ],
                ),
                // 删除按钮
                IconButton(
                  icon: const Icon(Icons.delete_outline, color: Colors.red),
                  onPressed: () {
                    _removeItem(index);
                  },
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建底部结算栏
  /// 包含全选、总价、结算按钮等功能
  Widget _buildCheckoutBar() {
    // 计算选中商品的总价
    final selectedItems = _cartItems.where((item) => item['selected']).toList();
    final totalPrice = selectedItems.fold<double>(
      0,
      (sum, item) => sum + (item['price'] * item['quantity']),
    );

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surface,
        border: Border(
          top: BorderSide(
            color: Theme.of(context).colorScheme.outline.withOpacity(0.2),
          ),
        ),
      ),
      child: SafeArea(
        child: Row(
          children: [
            // 全选功能
            Row(
              children: [
                Checkbox(
                  value: _selectAll,
                  onChanged: (value) {
                    setState(() {
                      _selectAll = value!;
                      // 将所有商品设置为全选状态
                      for (var item in _cartItems) {
                        item['selected'] = value;
                      }
                    });
                  },
                ),
                const Text('全选'),
              ],
            ),
            const SizedBox(width: 16),
            // 总价和商品数量信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  // 总价显示
                  Text(
                    '合计: ¥${totalPrice.toStringAsFixed(2)}',
                    style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                      color: Theme.of(context).colorScheme.primary,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  // 选中商品数量
                  Text(
                    '已选择 ${selectedItems.length} 件商品',
                    style: Theme.of(
                      context,
                    ).textTheme.bodySmall?.copyWith(color: Colors.grey[600]),
                  ),
                ],
              ),
            ),
            const SizedBox(width: 16),
            // 结算按钮
            ElevatedButton(
              onPressed: selectedItems.isNotEmpty ? _checkout : null,
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(
                  horizontal: 24,
                  vertical: 12,
                ),
              ),
              child: const Text('结算'),
            ),
          ],
        ),
      ),
    );
  }

  /// 更新全选状态
  /// 检查是否所有商品都被选中
  void _updateSelectAll() {
    setState(() {
      _selectAll = _cartItems.every((item) => item['selected']);
    });
  }

  /// 删除商品
  /// 显示确认对话框，确认后删除指定商品
  void _removeItem(int index) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除 ${_cartItems[index]['name']} 吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              setState(() {
                _cartItems.removeAt(index);
                _updateSelectAll(); // 更新全选状态
              });
              Navigator.pop(context);
            },
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 清空购物车
  /// 显示确认对话框，确认后清空所有商品
  void _clearCart() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认清空'),
        content: const Text('确定要清空购物车吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              setState(() {
                _cartItems.clear();
                _selectAll = false;
              });
              Navigator.pop(context);
            },
            child: const Text('清空'),
          ),
        ],
      ),
    );
  }

  /// 结算功能
  /// 显示结算确认对话框
  void _checkout() {
    final selectedItems = _cartItems.where((item) => item['selected']).toList();
    final totalPrice = selectedItems.fold<double>(
      0,
      (sum, item) => sum + (item['price'] * item['quantity']),
    );

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认结算'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('商品数量: ${selectedItems.length} 件'),
            Text('总金额: ¥${totalPrice.toStringAsFixed(2)}'),
            const SizedBox(height: 16),
            const Text('确定要结算吗？'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              // 显示结算成功提示
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('结算成功！'),
                  backgroundColor: Colors.green,
                ),
              );
              // 这里可以添加实际的结算逻辑
            },
            child: const Text('确认结算'),
          ),
        ],
      ),
    );
  }
}
